<template>
  <div class="doctor-list-page">
    <div class="toolbar">
      <el-button type="primary" @click="openAddModal">新增医生</el-button>
      <el-button @click="handleExport">导出</el-button>
      <el-input v-model="search" placeholder="搜索姓名/手机号" class="search-input" clearable @clear="handleSearch"
        @keyup.enter="handleSearch" />
      <el-select v-model="filterDept" placeholder="科室筛选" class="filter-select" clearable @change="handleSearch">
        <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
      </el-select>
      <el-select v-model="filterStatus" placeholder="状态筛选" class="filter-select" clearable @change="handleSearch">
        <el-option label="启用" value="active" />
        <el-option label="禁用" value="inactive" />
      </el-select>
    </div>
    <el-table :data="pagedDoctors" style="width: 100%" border @selection-change="handleSelectionChange"
      :row-key="row => row.id">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          {{ row.gender || '未填写' }}
        </template>
      </el-table-column>
      <el-table-column prop="department" label="科室" width="150" />
      <el-table-column prop="category" label="类别" width="120" />
      <el-table-column prop="specialty" label="专业" width="180" />
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="phone" label="手机号" width="140">
        <template #default="{ row }">
          {{ row.phone || '未填写' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="140">
        <template #default="{ row }">
          <div class="status-container">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
              @change="val => handleStatusChange(row, val)" size="small" />
            <el-tag v-if="row.status === 1" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="row.status === 0" type="info" size="small">禁用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="340">
        <template #default="{ row }">
          <el-button size="small" @click="openEditModal(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="goDetail(row)">详情</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="small" @click="handleResetPwd(row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="filteredDoctors.length"
        :page-size="pageSize" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 添加/编辑医生弹窗 -->
    <el-dialog :title="modalTitle" v-model="modalVisible" width="600px" @close="resetModal">
      <el-form :model="modalForm" label-width="90px">
        <el-form-item label="姓名">
          <el-input v-model="modalForm.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="modalForm.gender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="科室">
          <el-cascader v-model="modalForm.deptCascader" :options="cascaderOptions" placeholder="请选择科室" clearable
            filterable :props="{ expandTrigger: 'hover' }" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="modalForm.title" placeholder="请选择">
            <el-option label="主任医师" value="主任医师" />
            <el-option label="副主任医师" value="副主任医师" />
            <el-option label="主治医师" value="主治医师" />
            <el-option label="住院医师" value="住院医师" />
            <el-option label="医师" value="医师" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="modalForm.phone" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="modalForm.status" active-value="active" inactive-value="inactive" />
        </el-form-item>
        <el-form-item label="照片">
          <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange">
            <img v-if="modalForm.photo" :src="modalForm.photo" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input v-model="modalForm.intro" type="textarea" :rows="2" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="擅长">
          <el-input v-model="modalForm.goodAt" placeholder="如：高血压、糖尿病等" />
        </el-form-item>
        <el-form-item label="证件图片">
          <el-upload action="" list-type="picture-card" :file-list="certFileList" :on-preview="handleCertPreview"
            :on-remove="handleCertRemove" :on-change="handleCertChange" :before-upload="beforeCertUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog v-model="certPreviewVisible" width="400px">
            <img :src="certPreviewImg" style="width:100%" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modalVisible = false">取消</el-button>
        <el-button type="primary" @click="handleModalOk">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDoctorList, updateDoctor } from '@/api/doctor'

interface Department {
  id: string
  name: string
  children?: { id: string; name: string }[]
}
interface Doctor {
  id: number
  name: string
  gender: string
  departmentId: string
  departmentName: string
  title: string
  phone: string
  status: 'active' | 'inactive'
  photo?: string
  intro?: string
  goodAt?: string
  certImages?: string[]
  departmentParentId?: string
  deptCascader?: string[]
}

const departments = ref<Department[]>([
  {
    id: '1', name: '内科', children: [
      { id: '1-1', name: '心血管内科' },
      { id: '1-2', name: '呼吸内科' },
      { id: '1-3', name: '消化内科' }
    ]
  },
  {
    id: '2', name: '外科', children: [
      { id: '2-1', name: '普外科' },
      { id: '2-2', name: '骨科' },
      { id: '2-3', name: '神经外科' }
    ]
  },
  {
    id: '3', name: '妇产科', children: [
      { id: '3-1', name: '妇科' },
      { id: '3-2', name: '产科' }
    ]
  },
  {
    id: '4', name: '儿科', children: [
      { id: '4-1', name: '新生儿科' },
      { id: '4-2', name: '小儿内科' }
    ]
  },
  {
    id: '5', name: '眼科', children: [
      { id: '5-1', name: '眼底病科' },
      { id: '5-2', name: '白内障科' }
    ]
  }
])
const doctors = ref<Doctor[]>([])
onMounted(async () => {
  try {
    const res = await getDoctorList()
    if (res && res.data) {
      doctors.value = res.data
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
})

const search = ref('')
const filterDept = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selected = ref<Doctor[]>([])

const modalVisible = ref(false)
const modalForm = ref<any>({
  name: '', gender: '', departmentParentId: '', departmentId: '', departmentName: '', title: '', phone: '', status: 'active',
  photo: '', intro: '', goodAt: '', certImages: [], deptCascader: []
})
const editingId = ref<number | null>(null)
const modalTitle = computed(() => editingId.value ? '编辑医生' : '新增医生')

const certFileList = ref<any[]>([])
const certPreviewVisible = ref(false)
const certPreviewImg = ref('')

const cascaderOptions = ref<any[]>([])
onMounted(async () => {
  const res = await fetch('/1.json')
  const json = await res.json()
  cascaderOptions.value = (json.departments.outpatient || []).map((item: any) => ({
    label: item.level1,
    value: item.level1,
    children: (item.level2 || []).map((sub: string) => ({ label: sub, value: sub }))
  }))
})

const filteredDoctors = computed(() => {
  let arr = doctors.value
  if (search.value) {
    const s = search.value.trim()
    arr = arr.filter(d => d.name.includes(s) || d.phone.includes(s))
  }
  if (filterDept.value) {
    arr = arr.filter(d => d.departmentId === filterDept.value)
  }
  if (filterStatus.value) {
    arr = arr.filter(d => d.status === filterStatus.value)
  }
  return arr
})
const pagedDoctors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredDoctors.value.slice(start, start + pageSize.value)
})
const router = useRouter()

function handleSearch() {
  currentPage.value = 1
}
function handleSizeChange(size: number) {
  pageSize.value = size
  currentPage.value = 1
}
function handleCurrentChange(page: number) {
  currentPage.value = page
}
function handleSelectionChange(val: Doctor[]) {
  selected.value = val
}
function openAddModal() {
  editingId.value = null
  modalForm.value = { name: '', gender: '', departmentParentId: '', departmentId: '', departmentName: '', title: '', phone: '', status: 'active', photo: '', intro: '', goodAt: '', certImages: [], deptCascader: [] }
  certFileList.value = []
  modalVisible.value = true
}
function openEditModal(row: Doctor) {
  editingId.value = row.id
  modalForm.value = { ...row }
  if (row.departmentParentId && row.departmentId) {
    modalForm.value.deptCascader = [row.departmentParentId, row.departmentId]
  } else if (row.departmentName) {
    let found = false
    for (const group of cascaderOptions.value) {
      if (group.children?.some((c: any) => c.value === row.departmentName)) {
        modalForm.value.deptCascader = [group.value, row.departmentName]
        found = true
        break
      }
    }
    if (!found) modalForm.value.deptCascader = []
  } else {
    modalForm.value.deptCascader = []
  }
  certFileList.value = (row.certImages || []).map((url: string, idx: number) => ({ name: `证件${idx + 1}`, url }))
  modalVisible.value = true
}
function handleModalOk() {
  if (!modalForm.value.name || !modalForm.value.gender || !modalForm.value.deptCascader || modalForm.value.deptCascader.length !== 2) {
    ElMessage.warning('请填写完整信息')
    return
  }
  modalForm.value.departmentParentId = modalForm.value.deptCascader[0]
  modalForm.value.departmentId = modalForm.value.deptCascader[1]
  modalForm.value.departmentName = modalForm.value.deptCascader[1]
  if (editingId.value) {
    // 编辑
    const idx = doctors.value.findIndex(d => d.id === editingId.value)
    if (idx !== -1) {
      doctors.value[idx] = { ...modalForm.value, id: editingId.value }
      ElMessage.success('编辑成功')
    }
  } else {
    // 添加
    const newId = Math.max(...doctors.value.map(d => d.id), 0) + 1
    doctors.value.push({ ...modalForm.value, id: newId })
    ElMessage.success('添加成功')
  }
  modalVisible.value = false
}
function resetModal() {
  editingId.value = null
  modalForm.value = { name: '', gender: '', departmentParentId: '', departmentId: '', departmentName: '', title: '', phone: '', status: 'active', photo: '', intro: '', goodAt: '', certImages: [], deptCascader: [] }
  certFileList.value = []
}
function handleDelete(row: Doctor) {
  ElMessageBox.confirm(`确定要删除医生 ${row.name} 吗？`, '提示', { type: 'warning' })
    .then(() => {
      doctors.value = doctors.value.filter(d => d.id !== row.id)
      ElMessage.success('删除成功')
    })
}
function handleExport() {
  // 简单导出为CSV
  const header = '姓名,性别,科室,职称,手机号,状态\n'
  const rows = selected.value.length ? selected.value : doctors.value
  const content = rows.map(d => `${d.name},${d.gender},${d.departmentName},${d.title},${d.phone},${d.status === 'active' ? '启用' : '禁用'}`).join('\n')
  const blob = new Blob([header + content], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'doctors.csv'
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}
function handleResetPwd(row: Doctor) {
  ElMessageBox.confirm(`确定要重置医生 ${row.name} 的登录密码？`, '提示', { type: 'warning' })
    .then(() => {
      ElMessage.success('密码已重置为123456')
    })
}
function handleStatusChange(row: Doctor, val: 'active' | 'inactive') {
  row.status = val
  updateDoctor(row)
  ElMessage.success(`医生${row.name}已${val === 'active' ? '启用' : '禁用'}`)
}
function goDetail(row: Doctor) {
  router.push(`/admin/doctor/${row.id}`)
}
function beforeAvatarUpload(file: File) {
  const isImg = file.type.startsWith('image/')
  if (!isImg) ElMessage.error('只能上传图片')
  return isImg
}
function handleAvatarChange(file: any) {
  const reader = new FileReader()
  reader.onload = e => { modalForm.value.photo = e.target?.result as string }
  reader.readAsDataURL(file.raw)
}
function beforeCertUpload(file: File) {
  const isImg = file.type.startsWith('image/')
  if (!isImg) ElMessage.error('只能上传图片')
  return isImg
}
function handleCertChange(file: any, fileList: any[]) {
  certFileList.value = fileList
  modalForm.value.certImages = fileList.map(f => f.url || f.preview || '')
}
function handleCertPreview(file: any) {
  certPreviewImg.value = file.url || file.preview || ''
  certPreviewVisible.value = true
}
function handleCertRemove(file: any, fileList: any[]) {
  certFileList.value = fileList
  modalForm.value.certImages = fileList.map(f => f.url || f.preview || '')
}
</script>
<style scoped>
.doctor-list-page {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 18px;
}

.search-input {
  width: 200px;
}

.filter-select {
  width: 140px;
}

.pagination {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 8px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
}
</style>